<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        height: 100vh;
        display: flex;
        justify-content: center;
      }
      #app {
        overflow: hidden;
        margin: auto;
        width: 30%;
        height: 600px;
        background-color: #eee;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow-y: scroll;
      }
      img {
        margin-bottom: 8px;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>

    <script>
      const root = document.getElementById("app");
      let o = 0;
      const fragment = document.createDocumentFragment();
      for (let i = 0; i < 2000; i++) {
        const img = document.createElement("img");
        img.setAttribute("width", 100);
        img.setAttribute("height", 100);
        img.setAttribute(
          "data-src",
          `https://c-ssl.duitang.com/uploads/blog/202109/24/20210924081215_63853.jpeg?${o}`
        );
        fragment.appendChild(img);
        o++;
      }
      root.appendChild(fragment);

      // root.addEventListener("scroll", (e) => lazyImgs(e.target));
      // function lazyImgs(target) {
      //   const imgs = document.querySelectorAll("#app img");
      //   for (let img of imgs) {
      //     // 方法一
      //     // if (img.offsetTop < target.clientHeight + target.scrollTop + 100) {
      //     //   img.src = img.getAttribute("data-src");
      //     // }
      //     // 方法二
      //     if (img.getBoundingClientRect().top < target.clientHeight + 100) {
      //       img.src = img.getAttribute("data-src");
      //     }
      //   }
      // }
      // lazyImgs(root);

      // 方法三
      const lazyImages = document.querySelectorAll("#app img");
      const observer = new IntersectionObserver((entries) => {
        console.log(entries);
        entries.forEach((entry) => {
          console.log(entry);
          if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.getAttribute("data-src");
            observer.unobserve(img);
          }
        });
      });
      lazyImages.forEach((img) => observer.observe(img));
    </script>
  </body>
</html>
